<template>
  <div class="script-config">
    <el-table :data="scriptConfigList" style="width: 100%" v-loading="loading">
      <el-table-column prop="scriptName" label="脚本名称" width="150" />
      <el-table-column prop="scriptType" label="脚本类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getScriptTypeTag(row.scriptType)">
            {{ getScriptTypeText(row.scriptType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="scriptLanguage" label="脚本语言" width="100">
        <template #default="{ row }">
          <el-tag>{{ row.scriptLanguage }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="version" label="版本" width="80" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="info" link @click="handleView(row)">查看</el-button>
          <el-button 
            :type="row.status === 1 ? 'danger' : 'success'" 
            link 
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pageInfo.pageNum"
      v-model:page-size="pageInfo.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑脚本配置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="scriptFormRef"
        :model="scriptForm"
        :rules="scriptRules"
        label-width="100px"
      >
        <el-form-item label="脚本名称" prop="scriptName">
          <el-input v-model="scriptForm.scriptName" placeholder="请输入脚本名称" />
        </el-form-item>
        <el-form-item label="脚本类型" prop="scriptType">
          <el-select v-model="scriptForm.scriptType" placeholder="请选择脚本类型" style="width: 100%">
            <el-option label="数据转换" value="TRANSFORM" />
            <el-option label="数据验证" value="VALIDATION" />
            <el-option label="业务逻辑" value="BUSINESS" />
            <el-option label="自定义" value="CUSTOM" />
          </el-select>
        </el-form-item>
        <el-form-item label="脚本语言" prop="scriptLanguage">
          <el-select v-model="scriptForm.scriptLanguage" placeholder="请选择脚本语言" style="width: 100%">
            <el-option label="JavaScript" value="JavaScript" />
            <el-option label="Groovy" value="Groovy" />
            <el-option label="Python" value="Python" />
          </el-select>
        </el-form-item>
        <el-form-item label="脚本内容" prop="scriptContent">
          <el-input 
            v-model="scriptForm.scriptContent" 
            type="textarea" 
            :rows="10" 
            placeholder="请输入脚本内容"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="scriptForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入脚本描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="scriptForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看脚本内容对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="查看脚本"
      width="700px"
    >
      <el-form label-width="100px">
        <el-form-item label="脚本名称:">
          {{ currentScript.scriptName }}
        </el-form-item>
        <el-form-item label="脚本类型:">
          <el-tag :type="getScriptTypeTag(currentScript.scriptType)">
            {{ getScriptTypeText(currentScript.scriptType) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="脚本语言:">
          <el-tag>{{ currentScript.scriptLanguage }}</el-tag>
        </el-form-item>
        <el-form-item label="脚本内容:">
          <el-input 
            v-model="currentScript.scriptContent" 
            type="textarea" 
            :rows="15" 
            readonly
          />
        </el-form-item>
        <el-form-item label="描述:">
          {{ currentScript.description }}
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { getScriptConfigList, createScriptConfig, updateScriptConfig, deleteScriptConfig, updateScriptConfigStatus } from '@/api/engine'

const loading = ref(false)
const scriptConfigList = ref<any[]>([])
const total = ref(0)

const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10
})

const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const submitLoading = ref(false)
const scriptFormRef = ref<FormInstance>()

const scriptForm = reactive({
  id: undefined as number | undefined,
  scriptName: '',
  scriptType: 'TRANSFORM',
  scriptLanguage: 'JavaScript',
  scriptContent: '',
  version: '1.0.0',
  status: 1,
  description: ''
})

const currentScript = reactive({
  scriptName: '',
  scriptType: '',
  scriptLanguage: '',
  scriptContent: '',
  description: ''
})

const scriptRules: FormRules = {
  scriptName: [{ required: true, message: '请输入脚本名称', trigger: 'blur' }],
  scriptType: [{ required: true, message: '请选择脚本类型', trigger: 'change' }],
  scriptLanguage: [{ required: true, message: '请选择脚本语言', trigger: 'change' }],
  scriptContent: [{ required: true, message: '请输入脚本内容', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const dialogTitle = computed(() => 
  scriptForm.id ? '编辑脚本配置' : '新增脚本配置'
)

const getScriptTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    'TRANSFORM': 'primary',
    'VALIDATION': 'success',
    'BUSINESS': 'warning',
    'CUSTOM': 'info'
  }
  return tagMap[type] || 'info'
}

const getScriptTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    'TRANSFORM': '数据转换',
    'VALIDATION': '数据验证',
    'BUSINESS': '业务逻辑',
    'CUSTOM': '自定义'
  }
  return textMap[type] || type
}

const fetchScriptConfigList = async () => {
  loading.value = true
  try {
    const response = await getScriptConfigList(pageInfo)
    scriptConfigList.value = response.records
    total.value = response.total
  } catch (error) {
    ElMessage.error('获取脚本配置列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  scriptForm.id = undefined
  scriptForm.scriptName = ''
  scriptForm.scriptType = 'TRANSFORM'
  scriptForm.scriptLanguage = 'JavaScript'
  scriptForm.scriptContent = ''
  scriptForm.version = '1.0.0'
  scriptForm.status = 1
  scriptForm.description = ''
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  scriptForm.id = row.id
  scriptForm.scriptName = row.scriptName
  scriptForm.scriptType = row.scriptType
  scriptForm.scriptLanguage = row.scriptLanguage
  scriptForm.scriptContent = row.scriptContent
  scriptForm.version = row.version
  scriptForm.status = row.status
  scriptForm.description = row.description || ''
  dialogVisible.value = true
}

const handleView = (row: any) => {
  currentScript.scriptName = row.scriptName
  currentScript.scriptType = row.scriptType
  currentScript.scriptLanguage = row.scriptLanguage
  currentScript.scriptContent = row.scriptContent
  currentScript.description = row.description || ''
  viewDialogVisible.value = true
}

const handleToggleStatus = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}脚本"${row.scriptName}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await updateScriptConfigStatus(row.id, row.status === 1 ? 0 : 1)
    ElMessage.success(`${row.status === 1 ? '禁用' : '启用'}成功`)
    fetchScriptConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除脚本"${row.scriptName}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await deleteScriptConfig(row.id)
    ElMessage.success('删除成功')
    fetchScriptConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!scriptFormRef.value) return
  
  try {
    await scriptFormRef.value.validate()
    submitLoading.value = true
    
    if (scriptForm.id) {
      await updateScriptConfig(scriptForm.id, scriptForm)
      ElMessage.success('更新成功')
    } else {
      await createScriptConfig(scriptForm)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchScriptConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  scriptFormRef.value?.resetFields()
}

const handleSizeChange = (val: number) => {
  pageInfo.pageSize = val
  fetchScriptConfigList()
}

const handleCurrentChange = (val: number) => {
  pageInfo.pageNum = val
  fetchScriptConfigList()
}

onMounted(() => {
  fetchScriptConfigList()
})
</script>

<style scoped>
.script-config {
  padding: 20px;
}
</style>